"""
基础功能测试脚本
用于验证各个模块的基本功能
"""
import asyncio
import os
from dotenv import load_dotenv
from llm_integration import LLMService
from code_analyzer import CodeAnalyzer
from utils import validate_code_input, format_quality_report

load_dotenv()


async def test_llm_service():
    """测试LLM服务"""
    print("=" * 50)
    print("测试LLM服务")
    print("=" * 50)
    
    llm_service = LLMService()
    
    # 测试代码质量分析
    test_code = """
def calculate_total(items):
    total = 0
    for item in items:
        total = total + item.price
    return total
"""
    
    try:
        result = await llm_service.analyze_code_quality(
            code=test_code,
            language="python"
        )
        print("代码质量分析结果:")
        print(format_quality_report(result))
        print("\n")
    except Exception as e:
        print(f"测试失败: {str(e)}\n")


async def test_code_analyzer():
    """测试代码分析器"""
    print("=" * 50)
    print("测试代码分析器")
    print("=" * 50)
    
    llm_service = LLMService()
    analyzer = CodeAnalyzer(llm_service)
    
    test_code = """
def process_data(data):
    result = []
    for i in range(len(data)):
        if data[i] > 0:
            result.append(data[i] * 2)
    return result
"""
    
    try:
        result = await analyzer.analyze_code(
            code=test_code,
            language="python"
        )
        print("分析结果:")
        if "error" not in result:
            print(f"质量评分: {result.get('score', 'N/A')}")
            print(f"问题数量: {len(result.get('issues', []))}")
        else:
            print(f"错误: {result.get('error')}")
        print("\n")
    except Exception as e:
        print(f"测试失败: {str(e)}\n")


def test_utils():
    """测试工具函数"""
    print("=" * 50)
    print("测试工具函数")
    print("=" * 50)
    
    # 测试输入验证
    is_valid, error = validate_code_input("", "python")
    print(f"空代码验证: {is_valid}, 错误: {error}")
    
    is_valid, error = validate_code_input("print('hello')", "python")
    print(f"有效代码验证: {is_valid}, 错误: {error}")
    
    is_valid, error = validate_code_input("print('hello')", "invalid_lang")
    print(f"无效语言验证: {is_valid}, 错误: {error}")
    print("\n")


async def main():
    """主测试函数"""
    print("\n开始基础功能测试...\n")
    
    # 检查API密钥
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key or api_key == "sk-xxx":
        print("警告: 未配置DASHSCOPE_API_KEY，部分测试可能失败")
        print("请在.env文件中配置DASHSCOPE_API_KEY\n")
    
    # 测试工具函数（不需要API）
    test_utils()
    
    # 测试需要API的功能
    if api_key and api_key != "sk-xxx":
        await test_llm_service()
        await test_code_analyzer()
    else:
        print("跳过需要API的测试（未配置API密钥）\n")
    
    print("测试完成！")


if __name__ == "__main__":
    asyncio.run(main())

